package com.skywolf.chem.common.interceptor;

import com.skywolf.chem.common.context.LoginUser;
import com.skywolf.chem.common.context.RequestContext;
import com.skywolf.chem.common.enums.ResponseCodeEnum;
import com.skywolf.chem.common.sysconfig.exception.BizException;
import com.skywolf.chem.common.sysconfig.utils.JWTUtils;
import com.skywolf.chem.customer.entity.Customer;
import com.skywolf.chem.customer.service.ICustomerService;
import com.skywolf.chem.usercenter.entity.User;
import com.skywolf.chem.usercenter.service.IUserService;
import com.skywolf.chem.utils.CryptUtil;
import com.skywolf.chem.utils.RequestConstans;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证拦截器
 */
@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserService userService;

    @Autowired
    ICustomerService customerService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            //是否是 预请求OPTIONS
            if ("OPTIONS".equals(request.getMethod())) {
                log.info("这是一次预请求----");
                return true;
            }
            //获取请求头的token
            String token = request.getHeader("AUTH-TOKEN");
            String platformType = request.getHeader("platform");
            String uid= request.getHeader("uid");
            if(StringUtils.isNotBlank(platformType)){
                if(platformType.equals("eduapi") ){
                    checkloginAccount(uid,token);
                }else{
                    throw new BizException(ResponseCodeEnum.HEADER_TOKEN);
                }
            }else{
                //获取token中的username
                String username = JWTUtils.getUsername(token);
                User user = userService.getByUsername(username);
                //验证token
                //JWTUtils.verify(token, username, user.getPassword());
                //将user设置在请求上下文中
                LoginUser loginUser = new LoginUser();
                BeanUtils.copyProperties(user, loginUser);
                //loginUser.setRemoteId(IpUtils.getIpAddr(request));//获取ip
                RequestContext.setLoginUser(loginUser);
            }
            return true;
        } catch (Exception e) {
            log.error("认证失败", e);
            throw new BizException(ResponseCodeEnum.INVALID_TOKEN);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestContext.removeLoginUser();
    }

    /**
     * 从Head中加载用户帐号信息,进行校验本地head信息是否合法
     * @return
     * @throws IOException
     */
    public boolean checkloginAccount(String user_id, String userToken) throws BizException {
        String accountDecode = CryptUtil.IMDes3Decode(userToken, RequestConstans.decode_pwd);//解密account字段
        String uid = null, loginAccount = null,pwd = null;
        if (StringUtils.isBlank(accountDecode) || StringUtils.isBlank(user_id)) {
            throw new BizException(ResponseCodeEnum.API_INVALID_TOKEN);
        }
        int index = accountDecode.indexOf('|');
        int index2 = accountDecode.indexOf('|', index + 1);
        int index3 = accountDecode.indexOf('|', index2 + 1);
        if (index > 0) {
            uid = accountDecode.substring(0, index);//提取uid
            loginAccount = accountDecode.substring(index + 1, index2);//登录账号
            pwd = accountDecode.substring(index2+1,index3);//密码
        }
        //token的uid跟header的uid不一致，踢出去
        if(!uid.equals(user_id)){
            throw new BizException(ResponseCodeEnum.INVALID_TOKEN);
        }
        //查询用户密码进行对比
        Customer userInfo = customerService.getById(Long.valueOf(user_id));
        if(!userInfo.getPassword().equals(pwd)){
            throw new BizException(ResponseCodeEnum.USER_INVALID_USERNAME_PASSWORD);
        }
        return true;
    }
}
